import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {RequestParam} from '../../entity/request-param';
import {InvokeUtils} from '../../utils/invoke-utils';

@Component({
    selector: 'app-invoke-request-param-table',
    templateUrl: './invoke-request-param-table.component.html',
    styleUrls: ['./invoke-request-param-table.component.css']
})
export class InvokeRequestParamTableComponent implements OnInit {

    @Input()
    params: RequestParam[];

    @Output() tableChange = new EventEmitter();

    /**
     * 是否允许添加字段
     * @type {boolean}
     */
    @Input()
    addable = true;

    constructor() {
    }

    ngOnInit() {
    }

    deleteItem(index: number) {
        InvokeUtils.deleteParams(this.params, index);
    }

    addItem() {
        InvokeUtils.addEmptyParamRow(this.params);
    }

    paramKeyChange() {
        InvokeUtils.checkParamRows(this.params);
    }

    changeItemValue(key: string, value: string) {
        value = value.trim();
        this.params.forEach(pathParam => {
            if (pathParam.key === key) {
                pathParam.value = value;
                const currentValue = pathParam.value;
                if (pathParam.rulePattern) {
                    pathParam.match = pathParam.rulePattern.test(pathParam.value);
                } else {
                    pathParam.match = true;
                }
                this.tableChange.emit();
            }
        });
    }
}
